জেনেরিক্স জাভার একটি শক্তিশালী বৈশিষ্ট্য যা টাইপ-সেইফ কোড লিখতে সহায়তা করে। জেনেরিক ইন্টারফেস ব্যবহার করে এমন ইন্টারফেস তৈরি করা যায় যা বিভিন্ন ধরনের ডেটার জন্য কাজ করতে পারে। এটি টাইপ কাস্টিং কমায় এবং কোডের পুনঃব্যবহারযোগ্যতা বাড়ায়।
Generic Interface সংজ্ঞা
একটি জেনেরিক ইন্টারফেস তৈরি করতে <T> ব্যবহার করা হয়, যেখানে T একটি টাইপ প্যারামিটার।
// Generic Interface Definition
public interface GenericInterface<T> {
void display(T data);
}
এখানে:
GenericInterface<T>হল একটি জেনেরিক ইন্টারফেস।Tটাইপ প্যারামিটার নির্দেশ করে।
Generic Interface Implementation
জেনেরিক ইন্টারফেস বাস্তবায়নের সময়, একটি নির্দিষ্ট টাইপ সরবরাহ করা যেতে পারে।
// Implementing the Generic Interface
public class StringPrinter implements GenericInterface<String> {
@Override
public void display(String data) {
System.out.println("String Data: " + data);
}
}
public class IntegerPrinter implements GenericInterface<Integer> {
@Override
public void display(Integer data) {
System.out.println("Integer Data: " + data);
}
}
Generic Interface with Generic Implementation
একটি ক্লাস জেনেরিক ইন্টারফেস বাস্তবায়ন করার সময় নিজেও জেনেরিক হতে পারে।
// Generic Implementation
public class GenericPrinter<T> implements GenericInterface<T> {
@Override
public void display(T data) {
System.out.println("Generic Data: " + data);
}
}
উদাহরণ ব্যবহার
public class Main {
public static void main(String[] args) {
// Specific Type Implementation
GenericInterface<String> stringPrinter = new StringPrinter();
stringPrinter.display("Hello, Java Generics!");
GenericInterface<Integer> integerPrinter = new IntegerPrinter();
integerPrinter.display(100);
// Generic Implementation
GenericInterface<Double> genericPrinter = new GenericPrinter<>();
genericPrinter.display(3.14);
}
}
আউটপুট:
String Data: Hello, Java Generics!
Integer Data: 100
Generic Data: 3.14
Generic Interfaces এর সুবিধা:
- টাইপ সেফটি: টাইপ মিসম্যাচ প্রতিরোধ করে।
- কোড পুনঃব্যবহারযোগ্যতা: একাধিক টাইপের জন্য একই কোড ব্যবহার করা যায়।
- কোড পরিষ্কার এবং রিডেবল: টাইপ কাস্টিং এড়ানো যায়।
জেনেরিক ইন্টারফেস জাভায় ফ্লেক্সিবিলিটি এবং টাইপ-সেফ কোডের জন্য অপরিহার্য। এটি বড় আকারের প্রজেক্টে কোডের রিডেবলিটি এবং মেনটেনেন্স সহজ করে।
Read more